package com.whately.core.base.config.interceptor;

import com.whately.core.base.annotation.VisitPermitAfterLogin;
import com.whately.core.base.annotation.IgnoreSession;
import com.whately.core.base.annotation.InnerApi;
import com.whately.core.base.annotation.InnerController;
import com.whately.core.base.constant.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import java.lang.reflect.Method;

/**
 *  通过的接口，
 *  1.内部api 或者内部controller， 拦截
 *  2.ignoreSession,放行
 */
@Component
public class NotNeedAccessApiUtil   {
    private final Logger logger = LoggerFactory.getLogger(NotNeedAccessApiUtil.class);

    //内部api
    public boolean isInner( Object o) {
        if(o.getClass().isAnnotationPresent(InnerController.class)){
            logger.error(" InnerController not allow access bean {}",o);
            return true;
        }
        //含有Inner注解的接口放行
        if(o.getClass().isAssignableFrom(HandlerMethod.class)){
            HandlerMethod handlerMethod = (HandlerMethod)o;

            Class cc = handlerMethod.getBeanType();

            if(cc!=null&&cc.isAnnotationPresent(InnerController.class)){
                return true;
            }

            Method bridgedMethod =handlerMethod.getMethod();
            if(bridgedMethod.isAnnotationPresent(InnerApi.class)){
                logger.error("inner api not access bean {}",o);
                return true;
            }
        }

        return false;
    }

    //忽略验证
    public boolean isIgnore( Object o) {
        //含有IgnoreSession注解的接口放行
        if(o.getClass().isAssignableFrom(HandlerMethod.class)){
            HandlerMethod handlerMethod = (HandlerMethod)o;
            Method bridgedMethod =handlerMethod.getMethod();
            if(bridgedMethod.isAnnotationPresent(IgnoreSession.class)){
                return true;
            }
        }

        return false;
    }

    //登录即可访问
    public boolean isPermitAfterLogin(LoginUser jwtUser, Object o) {

        //登录即放行
        if(jwtUser!=null&&o.getClass().isAssignableFrom(HandlerMethod.class)){
            HandlerMethod handlerMethod = (HandlerMethod)o;
            Method bridgedMethod =handlerMethod.getMethod();
            if(bridgedMethod.isAnnotationPresent(VisitPermitAfterLogin.class)){
                return true;
            }
        }

        return false;
    }
}
